package com.mogujie.tt.ui.activity;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.mogujie.tt.DB.entity.UserEntity;
import com.mogujie.tt.DB.sp.GesturespasswordSp;
import com.mogujie.tt.DB.sp.LoginSp;
import com.mogujie.tt.app.IMApplication;
import com.mogujie.tt.imservice.manager.IMLoginManager;
import com.mogujie.tt.imservice.service.IMService;
import com.mogujie.tt.imservice.support.IMServiceConnector;
import com.mogujie.tt.ui.widget.IMBaseImageView;
import com.mogujie.tt.utils.LockPatternUtils;
import com.mogujie.tt.utils.LockPatternView;

import com.mogujie.tt.R;
import java.util.List;

/**
 * Created by Administrator on 2015/10/26.
 */
public class UnlockGesturePasswordActivity extends Activity{

    private LockPatternView mLockPatternView;
    private int mFailedPatternAttemptsSinceLastTimeout = 0;
    private CountDownTimer mCountdownTimer = null;
    private Handler mHandler = new Handler();
    private TextView mHeadTextView;
    private Animation mShakeAnim;

    private TextView gesturepwd_unlock_forget,gesturepwd_unlock_failtip;
    private Toast mToast;

    private void showToast(CharSequence message) {
        if (null == mToast) {
            mToast = Toast.makeText(this, message, Toast.LENGTH_SHORT);
            mToast.setGravity(Gravity.CENTER, 0, 0);
        } else {
            mToast.setText(message);
        }

        mToast.show();
    }

    private IMServiceConnector imServiceConnector = new IMServiceConnector(){
        @Override
        public void onServiceDisconnected() {}

        @Override
        public void onIMServiceConnected() {
            IMService imService = imServiceConnector.getIMService();
            if (imService == null) {
                return;
            }
            if (!imService.getContactManager().isUserDataReady()) {
                logger.i("detail#contact data are not ready");
            } else {
                init(imService);
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        imServiceConnector.connect(this);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.tt_activity_unlockgesturepassword);
        mLockPatternView = (LockPatternView) this.findViewById(R.id.gesturepwd_unlock_lockview);
        mLockPatternView.setOnPatternListener(mChooseNewLockPatternListener);
        mLockPatternView.setTactileFeedbackEnabled(true);
        mHeadTextView = (TextView) findViewById(R.id.gesturepwd_unlock_text);
        gesturepwd_unlock_forget = (TextView) findViewById(R.id.gesturepwd_unlock_forget);
        gesturepwd_unlock_failtip = (TextView) findViewById(R.id.gesturepwd_unlock_failtip);
        img();
        mShakeAnim = AnimationUtils.loadAnimation(this, R.anim.shake_x);

    }

    private void img() {

        gesturepwd_unlock_forget.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //intent.FLAG_ACTIVITY_CLEAR_TOP;
                IMApplication.getInstance().getLockPatternUtils().Lockdelete();
                GesturespasswordSp.set(UnlockGesturePasswordActivity.this, GesturespasswordSp.getNUM(), "");
                GesturespasswordSp.set(UnlockGesturePasswordActivity.this,GesturespasswordSp.DELETE_LOCK, LoginSp.instance().getLockLoginId()+"Ttrue");
                IMLoginManager.instance().setKickout(false);
                IMLoginManager.instance().logOut();
                finish();
            }
        });

    }

    private void init(IMService imService) {

        if (imService == null) {
            return;
        }
        final UserEntity loginContact = imService.getLoginManager().getLoginInfo();
        if (loginContact == null) {
            return;
        }
        IMBaseImageView portraitImageView = (IMBaseImageView)findViewById(R.id.user_portrait);
        portraitImageView.setDefaultImageRes(R.drawable.tt_default_user_portrait_corner);
        portraitImageView.setCorner(15);
        portraitImageView.setImageResource(R.drawable.tt_default_user_portrait_corner);
        portraitImageView.setImageUrl(loginContact.getAvatar());
    }



    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mCountdownTimer != null)
            mCountdownTimer.cancel();
    }
    private Runnable mClearPatternRunnable = new Runnable() {
        public void run() {
            mLockPatternView.clearPattern();
        }
    };

    protected LockPatternView.OnPatternListener mChooseNewLockPatternListener = new LockPatternView.OnPatternListener() {

        public void onPatternStart() {
            mLockPatternView.removeCallbacks(mClearPatternRunnable);
            patternInProgress();
        }

        public void onPatternCleared() {
            mLockPatternView.removeCallbacks(mClearPatternRunnable);
        }

        public void onPatternDetected(List<LockPatternView.Cell> pattern) {
            if (pattern == null)
                return;
            if (IMApplication.getInstance().getLockPatternUtils().checkPattern(pattern)) {
                mLockPatternView
                        .setDisplayMode(LockPatternView.DisplayMode.Correct);
                finish();
            } else {
                mLockPatternView
                        .setDisplayMode(LockPatternView.DisplayMode.Wrong);
                if (pattern.size() >= LockPatternUtils.MIN_PATTERN_REGISTER_FAIL) {
                    mFailedPatternAttemptsSinceLastTimeout++;
                    int retry = LockPatternUtils.FAILED_ATTEMPTS_BEFORE_TIMEOUT
                            - mFailedPatternAttemptsSinceLastTimeout;
                    if (retry >= 0) {
                        if (retry == 0)
                            showToast("您已5次输错密码，请重新登录");
                        mHeadTextView.setText("密码错误，还可以再输入" + retry + "次");
                        mHeadTextView.setTextColor(Color.RED);
                        mHeadTextView.startAnimation(mShakeAnim);
                        gesturepwd_unlock_failtip.setVisibility(View.VISIBLE);
                    }

                }else{
                    showToast("输入长度不够，请重试");
                }

                if (mFailedPatternAttemptsSinceLastTimeout >= LockPatternUtils.FAILED_ATTEMPTS_BEFORE_TIMEOUT) {
                    IMApplication.getInstance().getLockPatternUtils().Lockdelete();
                    GesturespasswordSp.set(UnlockGesturePasswordActivity.this, GesturespasswordSp.getNUM(), "");
                    GesturespasswordSp.set(UnlockGesturePasswordActivity.this,GesturespasswordSp.DELETE_LOCK, LoginSp.instance().getLockLoginId()+"Ttrue");
                    IMLoginManager.instance().setKickout(false);
                    IMLoginManager.instance().logOut();
                    finish();
                } else {
                    mLockPatternView.postDelayed(mClearPatternRunnable, 2000);
                }
            }
        }

        public void onPatternCellAdded(List<LockPatternView.Cell> pattern) {

        }

        private void patternInProgress() {
        }
    };


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            moveTaskToBack(true);
            return true;
        }
        return super.onKeyDown(keyCode, event);

    }

}
